package com.company.cloud.work.modules.mgr.controller;

import java.time.LocalDateTime;
import java.util.function.Function;

import com.company.cloud.common.auth.annotation.StaffLogc;
import com.company.common.server.constant.IRelBusiType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.company.cloud.common.asserts.ValidatorUtils;
import com.company.cloud.common.auth.annotation.Authc;
import com.company.cloud.common.bean.BaseResult;
import com.company.cloud.common.bean.LoginSimpleUserInfo;
import com.company.cloud.common.constant.BaseConstant.EnabledEnum;
import com.company.cloud.common.constant.BaseConstant.YNEnum;
import com.company.cloud.common.constant.BaseReturnEnum;
import com.company.cloud.common.exception.BusinessException;
import com.company.cloud.common.utils.AuthContextUtils;
import com.company.cloud.common.utils.StrSplitUtils;
import com.company.cloud.user.modules.api.service.UserRemoteService;
import com.company.cloud.work.modules.base.entity.WorkNoticeInfo;
import com.company.cloud.work.modules.base.service.WorkNoticeInfoService;
import com.company.cloud.work.modules.cache.models.WorkNoticeModel;
import com.company.cloud.work.modules.cache.utils.CrmWorkChangeUtils;
import com.company.cloud.work.modules.mgr.controller.req.WorkNoticeQuery4PageParam;
import com.company.cloud.work.modules.mgr.controller.req.WorkNoticeSaveParam;
import com.company.cloud.work.modules.mgr.controller.req.WorkNoticeUpdateParam;
import com.company.cloud.work.modules.mgr.controller.req.WorkNoticeUpdatePubStateParam;
import com.company.cloud.work.modules.mgr.service.WorkReceiptMgrService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;


@Authc
@RestController
@RequestMapping("/mgr/crm/workNotice")
@Api(tags="CRM_Mgr_公告管理")
public class WorkNoticeMgrController {
	
	@Autowired
	private WorkNoticeInfoService workNoticeInfoService;
	@Autowired
	private UserRemoteService userRemoteService;
	@Autowired
	private WorkReceiptMgrService workReceiptMgrService;
	

	@PostMapping("/query")
	@ApiOperation(value="查询", response=WorkNoticeModel.class)
	public BaseResult query(@RequestBody WorkNoticeQuery4PageParam params) {
		LoginSimpleUserInfo userInfo= AuthContextUtils.getUser();
		IPage<WorkNoticeInfo> page =  workNoticeInfoService.page(
				new Page<>(params.getPage(), params.getRows()), 
				new QueryWrapper<WorkNoticeInfo>()
				 .eq("rows_state", EnabledEnum.ENABLED.getCode())
				 .eq("company_no", userInfo.getCompanyNo())
				 .eq(StringUtils.hasText(params.getTitle()), "title", params.getTitle())
				 .eq(StringUtils.hasText(params.getPubState()), "pub_state", params.getPubState())
				 .eq(StringUtils.hasText(params.getIsReceipt()), "is_receipt", params.getIsReceipt())
				);
		
		IPage<WorkNoticeModel> data=page.convert(new Function<WorkNoticeInfo, WorkNoticeModel>() {
			@Override
			public WorkNoticeModel apply(WorkNoticeInfo entity) {
				return CrmWorkChangeUtils.getWorkNoticeModel(entity,null);
			}
		});
		
		return BaseResult.ok(data);
	}
	
	@PostMapping("/add")
	@ApiOperation(value="新增", response=BaseResult.class)
	@StaffLogc(title = "新增公告", action = "新增公告", actionAdo = "公告管理")
	public BaseResult add(@RequestBody WorkNoticeSaveParam params) {
		ValidatorUtils.validate(params);
		LoginSimpleUserInfo userInfo= AuthContextUtils.getUser();
		WorkNoticeInfo entity=new WorkNoticeInfo();
		entity.setCompanyNo(userInfo.getCompanyNo());
		entity.setTitle(params.getTitle());
		entity.setContent(params.getContent());
		entity.setShowScopeType(params.getShowScopeType());
		entity.setShowScope(StrSplitUtils.list2string_prefix(params.getShowScope()));
		entity.setIsReceipt(params.getIsReceipt());
		entity.setPubState(params.getPubState());
		entity.setPubDate(LocalDateTime.now());
		entity.addCreateParam(userInfo);
		entity.addEditParam(userInfo);
		workNoticeInfoService.save(entity);
		return BaseResult.ok();
	} 
	
	
	@PostMapping("/edit")
	@ApiOperation(value="修改", response=BaseResult.class)
	@StaffLogc(title = "修改公告", action = "修改公告", actionAdo = "公告管理")
	public BaseResult edit(@RequestBody WorkNoticeUpdateParam params) {
		ValidatorUtils.validate(params);
		WorkNoticeInfo entity=workNoticeInfoService.getById(params.getId());
		if (entity == null || EnabledEnum.DISABLED.getCode().equals(entity.getRowsState())) {
			throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
		}
		if(YNEnum.YES.getCode().equals(YNEnum.YES.getCode())) {
			throw new BusinessException("");
		}
		LoginSimpleUserInfo userInfo= AuthContextUtils.getUser();
		entity.setTitle(params.getTitle());
		entity.setContent(params.getContent());
		entity.setShowScopeType(params.getShowScopeType());
		entity.setShowScope(StrSplitUtils.list2string_prefix(params.getShowScope()));
		entity.setIsReceipt(params.getIsReceipt());
		entity.setPubState(params.getPubState());
		entity.setPubDate(LocalDateTime.now());
		entity.addEditParam(userInfo);
		workNoticeInfoService.updateById(entity);
		return BaseResult.ok();
	}
	
	@GetMapping("/get")
	@ApiOperation(value="获取", response=WorkNoticeModel.class)
	public BaseResult get(@RequestParam("id")Integer id) {
		WorkNoticeInfo entity=workNoticeInfoService.getById(id);
		if (entity == null || EnabledEnum.DISABLED.getCode().equals(entity.getRowsState())) {
			throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
		}
		LoginSimpleUserInfo userInfo= AuthContextUtils.getUser();
//		Set<Integer> userIds = new HashSet<Integer>();
//		Map<Integer, UserSimple> userMap = userRemoteService.getUserMapByIds(userIds);
		
		WorkNoticeModel data=CrmWorkChangeUtils.getWorkNoticeModel(entity,null);
		if(YNEnum.YES.getCode().equals(entity.getIsReceipt())) {
			workReceiptMgrService.save(IRelBusiType.CRM_Notice_ID, entity.getId().toString(), null, userInfo);
		}
		return BaseResult.ok(data);
	}
	
	@PostMapping("/updatePubState")
	@ApiOperation(value="修改上下架状态", response=BaseResult.class)
	@StaffLogc(title = "修改上下架状态", action = "修改上下架状态", actionAdo = "公告管理")
	public BaseResult updatePubState(@RequestBody WorkNoticeUpdatePubStateParam params) {
		ValidatorUtils.validate(params);
		WorkNoticeInfo entity=workNoticeInfoService.getById(params.getId());
		if (entity == null || EnabledEnum.DISABLED.getCode().equals(entity.getRowsState())) {
			throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
		}
		if(entity.getPubState().equals(params.getPubState())) {
			return BaseResult.ok();
		}
		LoginSimpleUserInfo userInfo= AuthContextUtils.getUser();
		entity.setPubState(params.getPubState());
		entity.setPubDate(LocalDateTime.now());
		entity.addEditParam(userInfo);
		workNoticeInfoService.updateById(entity);
		return BaseResult.ok();
	}
	
	@GetMapping("/remove")
	@ApiOperation(value="删除", response=BaseResult.class)
	@StaffLogc(title = "删除公告", action = "删除公告", actionAdo = "公告管理")
	public BaseResult remove(@RequestParam("id")Integer id) {
		WorkNoticeInfo entity=workNoticeInfoService.getById(id);
		if (entity == null || EnabledEnum.DISABLED.getCode().equals(entity.getRowsState())) {
			throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
		}
		if(YNEnum.YES.getCode().equals(YNEnum.YES.getCode())) {
			throw new BusinessException("");
		}
		LoginSimpleUserInfo userInfo= AuthContextUtils.getUser();
		entity.setRowsState(EnabledEnum.DISABLED.getCode());
		entity.addEditParam(userInfo);
		workNoticeInfoService.updateById(entity);
		return BaseResult.ok();
	}
	
}
